package com.zhida.jiyangcenter.account

import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.manager.app
import chooongg.base.utils.*
import chooongg.http.APIException
import chooongg.http.HttpCallback
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.WebNoTokenActivity
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.mian.MainActivity
import com.zhida.jiyangcenter.utils.SP
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_login_phone.*
import kotlinx.android.synthetic.main.activity_login_phone.btn_wechat
import kotlinx.android.synthetic.main.activity_login_phone.title_bar
import kotlinx.android.synthetic.main.activity_login_phone.tv_login_other
import kotlinx.android.synthetic.main.activity_login_phone.tv_login_xieyi
import kotlinx.android.synthetic.main.activity_login_phone.tv_title


@TitleBar(false)
@ContentLayout(R.layout.activity_login_phone)
class LoginPhoneActivity : BaseActivity() {
    var isAfter = false
    override fun initConfig(savedInstanceState: Bundle?) {
        val window = activity.window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        tv_title.setText("手机动态密码登录".style { } + "\n解锁更多功能  一站式管理你的健康".style {
            setTextSizeRelative(0.5f)
            setTextStyle(Typeface.NORMAL)
        })
        val styles = SpannableStringBuilder() //设置文字
        val s = "登录注册即代表同意《用户使用协议》《隐私政策说明条款》"
        styles.append(s)
        val clickableSpans = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity<WebNoTokenActivity> {
                    putExtra(
                        WebNoTokenActivity.URL,
                        "http://beauty.hebzd.com/static/xieyi/userAgreement.html"
                    )
                    putExtra(WebNoTokenActivity.TITLE, "用户使用协议")
                }
            }
        }
        styles.setSpan(clickableSpans, 9, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        val foregroundColorSpans = ForegroundColorSpan(Color.parseColor("#1296DB"))
        styles.setSpan(
            foregroundColorSpans,
            9,
            17,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        ) //配置给TextView
        val clickableSpan1 = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity<WebNoTokenActivity> {
                    putExtra(
                        WebNoTokenActivity.URL,
                        "http://beauty.hebzd.com/static/xieyi/privacy.html"
                    )
                    putExtra(WebNoTokenActivity.TITLE, "隐私政策说明条款")
                }
            }
        }
        styles.setSpan(clickableSpan1, 18, styles.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        val foregroundColorSpan1 = ForegroundColorSpan(Color.parseColor("#1296DB"))
        styles.setSpan(
            foregroundColorSpan1,
            18,
            styles.length,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        ) //配置给TextView
        tv_login_xieyi.movementMethod = LinkMovementMethod.getInstance()
        tv_login_xieyi.text = styles

        check_box.setOnClickListener {
            check_box.setChecked(!check_box.isChecked, true)
        }
        edit_phone.addTextChangedListener {
            if (it?.length == 11) {
                showTipLoading()
                lifecycleScope.request({
                    APIPay.service().mineUserJudge(edit_phone.text.toString())
                }, object : BaseAPI<MineUserJudgeEntity>() {
                    override fun onSuccess(t: MineUserJudgeEntity?, state: Int, msg: String) {
                        hideTipLoading()
                        isAfter = true
                        if (t?.status == "0") {
                            edit_yaoqingma.visible()
                        }
                    }

                    override fun onError(e: APIException) {
                        tipFail(e.eMessage)
                        hideTipLoading()
                        isAfter = true
                    }

                })

            }
        }
        btn_login.setOnClickListener {
            when {
                isAfter -> {
                }
                edit_phone.text.toString()
                    .isEmpty() -> showSoftInput(edit_phone).apply { tipWarn(R.string.login_phone_empty) }
                !edit_phone.text.toString()
                    .regex(RegexConstants.REGEX_MOBILE_EXACT) -> showSoftInput(edit_phone).apply {
                    tipWarn(
                        R.string.login_phone_wrong
                    )
                }
                !check_box.isChecked -> toast("请选阅读并同意《用户使用协议》《隐私政策说明条款》")
                else -> {
                    lifecycleScope.request({
                        APIAccount.service().sendCode(edit_phone.text.toString())
                    },
                        object : BaseAPI<Any>() {

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }

                            override fun onSuccess(t: Any?, state: Int, msg: String) {
                                startActivity<LoginCodeActivity> {
                                    putExtra("phone", edit_phone.text.toString())
                                    if (edit_yaoqingma.text.toString().isNotEmpty()) {
                                        putExtra("yaoqingma", edit_yaoqingma.text.toString())
                                    }
                                    putExtra(
                                        "wechat_openid",
                                        intent.getStringExtra("wechat_openid")
                                    )
                                }
                            }
                        })
                }
            }
        }
        iv_phone_clear.setOnClickListener { edit_phone.text = null }
        btn_login_esm.setOnClickListener {
            finish()
        }
        if (intent.getStringExtra("wechat_openid").isNullOrEmpty()) {
            tv_login_other.visible()
            btn_wechat.visible()
            tv_login_xieyi.visible()
            check_box.visible()
        } else {
            tv_login_other.gone()
            btn_wechat.gone()
            tv_login_xieyi.gone()
            check_box.gone()
        }
        btn_wechat.setOnClickListener {
            if (check_box.isChecked) {
                val wechat = ShareSDK.getPlatform(Wechat.NAME)
                if (wechat.isAuthValid) wechat.removeAccount(true)// 解除本地授权信息
                //SSO授权，传false默认是客户端授权
                wechat.SSOSetting(false);
                wechat.platformActionListener = object : PlatformActionListener {
                    override fun onComplete(
                        platform: Platform,
                        action: Int,
                        res: HashMap<String, Any>
                    ) {
                        showTipLoading("登录中")
                        if (action == Platform.ACTION_USER_INFOR) {
                            wechatLogin(res["openid"].toString())
                        }
                    }

                    override fun onCancel(p0: Platform?, p1: Int) {
                        toast("取消授权")
                    }

                    override fun onError(p0: Platform?, errorCode: Int, e: Throwable?) {
                        toast("授权失败\n错误码：$errorCode")
                        Log.e("SDFSDFSDF", "dfwetwesfsdf", e)
                        e?.printStackTrace()
                    }
                }
                wechat.showUser(null)
            } else {
                toast("请选阅读并同意《用户使用协议》《隐私政策说明条款》")
            }

        }
    }

    private fun wechatLogin(toString: String) {
        lifecycleScope.request({ APIAccount.service().weCharLogin(toString) },
            object : BaseAPI<LoginEntity>() {
                override fun onSuccess(loginEntity: LoginEntity?, state: Int, msg: String) {
                    hideTipLoading()
                    if (loginEntity == null) {

                    } else {
                        tipSuccess(msg)
                        SP.isLogin.put(true)
                        SP.key_id.put(loginEntity.key_id)
                        SP.account.put(loginEntity.account)
                        SP.avatar.put(loginEntity.avatar)
                        SP.EBusinessID.put(loginEntity.business_id)
                        SP.AppKey.put(loginEntity.app_key)
                        SP.ReqURL.put(loginEntity.req_url)
//                        if (!SP.ISYinsi.get()) {
//                            startActivity<WebNoTokenActivity> {
//                                putExtra(WebNoTokenActivity.URL, "http://beauty.hebzd.com/static/xieyi/privacy.html")
//                                putExtra(WebNoTokenActivity.TITLE, "隐私协议")
//                            }
//                        } else {
                        startActivity<MainActivity> { }
//                        }
                        for (i in app.activityStack.size - 1 downTo 0) {
                            if (app.activityStack[i] !is MainActivity) {
                                app.activityStack[i].finish()
                            }
                        }
                        finish()
                    }
                }

                override fun onError(e: APIException) {
                    hideTipLoading()
                    if (e.code == "-9") {
                        startActivity<LoginPhoneActivity> {
                            putExtra("wechat_openid", toString)
                        }
                    } else {
                        tipFail(e.eMessage)
                    }
                }

            })
    }
}